import React, { createContext, useReducer, useState } from 'react'
import { useLocation } from 'react-router-dom'

export const pathContext = createContext()

const { Provider } = pathContext

const reducer = (state, action) => {
  if (action.type === 'changePath') {
    return {
      path: action.path
    }
  }

  return state
}

export default function PathProvider(props) {
  const { pathname } = useLocation() 

  const [defaultState] = useState({
    path: pathname
  })
  
  const [state, dispatch] = useReducer(reducer, defaultState)

  return (
    <Provider
      value={{
        state,
        dispatch
      }}
    >
      {props.children}
    </Provider>
  )
}
